from django.conf import settings
from django.core.files.storage import Storage
from django.utils.deconstruct import deconstructible
from fdfs_client.client import Fdfs_client


# @deconstructible
class FastDFSStorage(Storage):
    def __init__(self, base_url=None, client_conf=None):

        if base_url is not None:
            self.base_url = base_url
        else:
            self.base_url = settings.FDFS_URL

        if client_conf is not None:
            self.client_conf = client_conf
        else:
            self.client_conf = settings.FDFS_CLIENT_CONF

    def _open(self, name, mode='rb'):
        # 打开文件
        pass

    def _save(self, name, content):
        # 保存文件
        # 建立fastdfs连接  # 连接七牛云
        c = Fdfs_client(self.client_conf)

        # 文件上传
        res = c.upload_by_buffer(content.read())

        # 判断上传状态
        if res['Status'] != 'Upload successed.':
            raise Exception('upload error')

        # 返回存储路径
        return res['Remote file_id']

    def url(self, name):
        # 拼接完整路径
        return self.base_url + name

    def exists(self, name):
        return False
